﻿using Nest;
using System;
using System.Collections.Generic;

namespace Infrastructure.ElasticSearch.ParentChilds
{
    public class PageBaseSpecification<T> : ISearchSpecification<ISearchRequest<T>> where T : class
    {
        private readonly int _page;
        private readonly int _from;
        private readonly int _size;
        private readonly ISearchSpecification<ISearchRequest<T>> _query;
        private readonly Func<SortDescriptor<T>, IPromise<IList<ISort>>> _sorts;

        public PageBaseSpecification(ISearchSpecification<ISearchRequest<T>> query, int page, int size,
            Func<SortDescriptor<T>, IPromise<IList<ISort>>> sorts = null)
        {
            _query = query ?? throw new ArgumentNullException($"{nameof(query)} cannot be null.");
            _sorts = sorts;
            _page = page > 0 ? page : 0;
            _size = size > 0 ? size : 10;
            _from = _page > 0 ? (_page - 1) * _size : 0;
        }

        public ISearchRequest<T> IsSatisfiedBy()
        {
            var search = new SearchDescriptor<T>()
                .Query(q => _query
                    .IsSatisfiedBy()
                    .Query
                )
                .From(_from)
                .Size(_size);

            if (_sorts != null)
            {
                return search.Sort(_sorts);
            }

            return search;
        }

    }
}